#include"SeqList.h"

//初始化
void  SLTnit(SL* ps)
{
	assert(ps);
	ps->a =(SLDataType*)malloc(sizeof(SLDataType)*INIT_CAPACITY);
	if (ps->a == NULL)
	{
		perror("malloc fail");
		return 1;
	}
	ps->size = 0;
	ps->capacity = INIT_CAPACITY;
}

//销毁
void SLDestroy(SL* ps)
{
	assert(ps);
	free(ps->a);
	ps->a == NULL;
	ps->capacity = ps->size = 0;
}

//打印顺序表
void SLPrint(SL* ps)
{
	assert(ps);
	for (int i = 0;i < ps->size;++i)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

//检查容量并决定是否扩容
void SLCheckCapacity(SL* ps)
{
	assert(ps);
	//检查容量够不够，不够则扩容
	if (ps->size == ps->capacity)
	{
		SLDataType* tmp = (SLDataType*)realloc(ps->a, sizeof(SLDataType) * ps->capacity * 2);//一般来说扩容2倍比较合适
		//检验是否开辟成功
		if (tmp == NULL)
		{
			perror("realloc fail");
			return 1;
		}
		ps->a = tmp;
		ps->capacity *= 2;
	}
}

//尾插
void SLPushBack(SL* ps, SLDataType x)
{
	//assert(ps);
	//SLCheckCapacity(ps);
	//ps->a[ps->size] = x;
	//ps->size++;

	SLInsert(ps, ps->size, x);
}

//尾删
void SLPopBack(SL* ps)
{
	assert(ps);
	//暴力检查
	assert(ps->size > 0);
	//温柔的检查
	/*if (ps->size == 0)
		return 1;*/
	//ps->a[ps->size - 1] = 0;
	//ps->size--;
	SLErase(ps, ps->size - 1);
}

//头插
void SLPushFront(SL* ps, SLDataType x)
{
	//assert(ps);
	//SLCheckCapacity(ps);

	//int end = ps->size - 1;
	//while (end >= 0)
	//{
	//	ps->a[end+1] = ps->a[end];
	//	--end;
	//}
	//ps->a[0] = x;
	//ps->size++;
	SLInsert(ps, 0, x);
}

//头删
void SLPopFront(SL* ps)
{
	//assert(ps);
	//assert(ps->size > 0);

	////从前往后来
	//int begin = 1;
	//while (begin < ps->size)
	//{
	//	ps->a[begin - 1] = ps->a[begin];
	//	++begin;
	//}
	//ps->size--;
	SLErase(ps, 0);
}

//某个位置插入
void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);

	SLCheckCapacity(ps);
	
	int end = ps->size-1;
	if (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[pos]=x;
	ps->size++;
}

//某个位置删除
void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);

	SLCheckCapacity(ps);

	int begin = pos + 1;
	while (begin < ps->size)
	{
		ps->a[begin] = ps->a[begin - 1];
		++begin;
	}
	ps->size--;
}

//查找
int SLFind(SL* ps, SLDataType x)
{
	assert(ps);
	for (int i = 0;i <ps->size;i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}